import os
from handlers import *


class AdminHandler(BaseHandler):
	@tornado.web.authenticated
	def get(self):
		pages = self.db.query(
			'SELECT * FROM pages ORDER by nav_order')
		
		self.render('admin.html', pages=pages)


class CreateHandler(BaseHandler, PageMixin):
	@tornado.web.authenticated
	def post(self):
		name = tornado.escape.to_unicode(self.get_argument('name'))
		page = self.save_page(
			name=name, raw='', html='')
		
		if not page:
			self.add_message("Page name '%s' already in use" % name, type=ERROR)
			self.redirect_to('admin')
			return
		
		self.add_message('Page created', type=SUCCESS)
		self.redirect_to('edit', page)


class EditHandler(BaseHandler, PageMixin, ProcessingMixin, UploadsMixin):
	@tornado.web.authenticated
	def get(self, slug):
		page = self.get_page(slug)
		
		if not page:
			raise tornado.web.HTTPError(404)
		
		uploads = self.db.query(
			'SELECT * FROM uploads WHERE page_id = %s '
			'ORDER BY created', page.id)
		
		self.render('edit.html', contents=page, uploads=uploads)
	
	@tornado.web.authenticated
	def post(self, slug):
		page_id = self.get_argument('page_id')
		name = tornado.escape.to_unicode(self.get_argument('name'))
		raw = tornado.escape.to_unicode(self.get_argument('raw', ''))
		processed = self.process_html(page_id, raw)
		
		page = self.save_page(
			id=page_id, name=name, raw=raw, html=processed,
			in_nav=int(bool(self.get_argument('in_nav', 0))))
		
		if not page:
			self.add_message("Page name '%s' already in use" % name, type=ERROR)
			self.redirect_to('edit', slug)
			return
		
		if 'files' in self.request.files:
			if not self.js_enabled:
				self.upload_files('files', page_id)
			else:
				logging.info('Files not uploaded with JavaScript enabled')
		
		self.add_message('Page saved', type=SUCCESS)
		self.redirect_to('edit', page)


class OrderHandler(BaseHandler):
	@tornado.web.authenticated
	def post(self):
		del self.request.arguments['_xsrf']
		
		values = ', '.join(['(%s, %s)' % (arg[0], arg[1][0]) \
				 for arg in self.request.arguments.items()])
		
		query = 'INSERT INTO pages (id, nav_order) VALUES %s ' \
				'ON DUPLICATE KEY UPDATE nav_order = VALUES(nav_order)' % values
		
		return self.db.execute(query)


class HideHandler(BaseHandler):
	@tornado.web.authenticated
	def post(self):
		page_id = self.get_argument('page_id')
		
		self.db.execute(
			'UPDATE pages SET hidden = not(hidden) WHERE id = %s', page_id)
		
		hidden = self.db.get(
			'SELECT hidden FROM pages WHERE id = %s', page_id).hidden
		
		self.write('(on)' if hidden is 0 else '(off)')


class DeleteHandler(BaseHandler, PageMixin):
	@tornado.web.authenticated
	def post(self):
		self.delete_page(self.get_argument('page_id'))
		self.add_message('Page deleted', type=SUCCESS)
		self.redirect_to('admin')


class UploadHandler(BaseHandler, UploadsMixin):
	@tornado.web.authenticated
	def post(self):
		html = []
		uploaded = self.upload_files('files', self.get_argument('page_id'))
		
		for upload in uploaded:
			html.append(self.render_string('upload.html', upload=upload))
		
		self.write({'uploads': html})


class DeleteUploadHandler(BaseHandler, UploadsMixin):
	@tornado.web.authenticated
	def post(self):
		upload_id = self.get_argument('upload_id')
		if not self.delete_upload(upload_id):
			raise tornado.web.HTTPError(500, 'Upload not deleted')
		
		if not self.js_enabled:
			self.add_message('Upload deleted', type=SUCCESS)
			self.redirect_to('edit', self.get_argument('page_slug'))
			return
		
		self.write(upload_id)


class ClearLinksHandler(BaseHandler):
	@tornado.web.authenticated
	def post(self):
		self.db.execute('TRUNCATE permalinks')
		self.add_message('Permalinks cleared', type=SUCCESS)
		self.redirect_to('prefs')


class PrefsHandler(BaseHandler):
	@tornado.web.authenticated
	def get(self):
		pages = self.db.query('SELECT * FROM pages ORDER BY nav_order')
		default = long(self.get_setting('default_page'))
		
		self.render('prefs.html', pages=pages, default=default)
	
	@tornado.web.authenticated
	def post(self):
		self.set_setting(
			'default_page',
			self.get_argument('default_page', None))
		
		self.add_message('Preferences saved', type=SUCCESS)
		self.redirect_to('prefs')